<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/Security.php';

class FileManager {
    private $db;
    private $uploadDir;
    private $allowedTypes = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'text/plain'
    ];

    public function __construct() {
        $this->db = getDBConnection();
        $this->uploadDir = __DIR__ . '/../uploads/';
        
        // 确保上传目录存在
        if (!file_exists($this->uploadDir)) {
            mkdir($this->uploadDir, 0755, true);
        }
    }

    public function uploadFile($file, $userId) {
        try {
            // 验证文件
            $errors = Security::validateFileUpload($file, $this->allowedTypes);
            if (!empty($errors)) {
                return ['success' => false, 'message' => implode(', ', $errors)];
            }

            // 生成安全的文件名
            $safeFileName = Security::generateSafeFileName($file['name']);
            $filePath = $this->uploadDir . $safeFileName;

            // 移动文件
            if (!move_uploaded_file($file['tmp_name'], $filePath)) {
                return ['success' => false, 'message' => '文件上传失败'];
            }

            // 记录到数据库
            $stmt = $this->db->prepare("INSERT INTO files (user_id, original_name, file_name, file_size, file_type, uploaded_at) VALUES (?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $userId,
                $file['name'],
                $safeFileName,
                $file['size'],
                $file['type']
            ]);

            return ['success' => true, 'message' => '文件上传成功'];
        } catch (Exception $e) {
            error_log("文件上传失败: " . $e->getMessage());
            return ['success' => false, 'message' => '文件上传失败，请稍后再试'];
        }
    }

    public function getUserFiles($userId) {
        try {
            $stmt = $this->db->prepare("SELECT * FROM files WHERE user_id = ? ORDER BY uploaded_at DESC");
            $stmt->execute([$userId]);
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            error_log("获取文件列表失败: " . $e->getMessage());
            return [];
        }
    }

    public function deleteFile($fileId, $userId) {
        try {
            // 验证文件所有权
            $stmt = $this->db->prepare("SELECT file_name FROM files WHERE id = ? AND user_id = ?");
            $stmt->execute([$fileId, $userId]);
            $file = $stmt->fetch();

            if (!$file) {
                return ['success' => false, 'message' => '文件不存在或无权删除'];
            }

            // 删除物理文件
            $filePath = $this->uploadDir . $file['file_name'];
            if (file_exists($filePath)) {
                unlink($filePath);
            }

            // 删除数据库记录
            $stmt = $this->db->prepare("DELETE FROM files WHERE id = ? AND user_id = ?");
            $stmt->execute([$fileId, $userId]);

            return ['success' => true, 'message' => '文件删除成功'];
        } catch (Exception $e) {
            error_log("文件删除失败: " . $e->getMessage());
            return ['success' => false, 'message' => '文件删除失败，请稍后再试'];
        }
    }

    public function getFileInfo($fileId, $userId) {
        try {
            $stmt = $this->db->prepare("SELECT * FROM files WHERE id = ? AND user_id = ?");
            $stmt->execute([$fileId, $userId]);
            return $stmt->fetch();
        } catch (PDOException $e) {
            error_log("获取文件信息失败: " . $e->getMessage());
            return null;
        }
    }
}
?> 